<?php

/**
 * Created by Reliese Model.
 */

namespace App\Models\Api;

use App\Models\Env\Host;
use App\Models\Env\HostEnv;
use App\Models\Module\ProductModule;
use App\Models\Projects\Product;
use App\Models\Projects\Project;
use App\Models\Projects\ProjectCate;
use App\Models\TestApi\TestParamRes;
use App\Models\TestApi\TestValidatorRes;
use Carbon\Carbon;
use App\Models\Eloquent;
/**
 * Class QtpApisValidator
 *
 * @property int $id
 * @property int $api_id
 * @property int $param_id
 * @property string|null $key
 * @property string $validator_value
 * @property string $created_adminer
 * @property string $updated_adminer
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 *
 * @package App\Models
 */
class ApisValidator extends Eloquent
{
	protected $table = 'apis_validator';

	protected $casts = [
		'api_id' => 'int',
		'param_id' => 'int'
	];

	protected $fillable = [
		'api_id',
		'param_id',
		'key',
		'validator_value',
		'created_adminer',
		'updated_adminer'
	];

    public static $fillables = [
        'api_id' => 'Api.ID',
        'param_id' => 'api参数.ID',
        'key' =>'验证返回结果key',
        'validator_value' => '验证返回结果值',
        'created_adminer' => '创建人',
        'updated_adminer' => '更新人',
    ];

    public function label()
    {

        $this->param = ApisParam::find($this->param_id)->param ?? '';
        if(!$api = Apis::find($this->api_id)) {
            return $this;
        }
        $this->headers = Apis::getHeaders($api) ?: [];
        list($this->host_env, $this->host_url) = ['', ''];
        if($api->host_id > 0) {
            $HostEnv = HostEnv::find($api->host_id);
            list($this->host_env, $this->host_url) = [
                $HostEnv->name ?? '',
                Host::where('host_env_id', $HostEnv->id)->where('enable', 1)->first()->http ?? ''
            ];
        }
        $this->cate_name = ProjectCate::find($api->cate_id)->name ?? '';
        $this->project_name = Project::find($api->project_id)->name ?? '';
        $this->product_name = Product::find($api->product_id)->name ?? '';
        $this->f_module_name = ProductModule::find($api->f_module_id)->name ?? '';
        $this->s_module_name = ProductModule::find($api->s_module_id)->name ?? '';
        $this->method_type_lable = Apis::$method_type_maps[$api->method_type] ?? '未知';
        $this->api = $api->api;
        $this->api_name = $api->name;
        $this->test_sum = TestValidatorRes::where('validator_id', $this->id)->count(); // 测试历史条数
        $this->recently_res = TestParamRes::where('param_id', $this->param_id)->orderByDesc('id')->first()?->res ?? null; // 最近一次测试返回值
        return $this;
    }
}
